<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  
  
    <meta name="keywords" content="前端,Vue.js,JavaScript,Node.js,小程序">
  
  
    <meta name="description" content="GuoYou.Li(李国有)的博客, 用于做学习过程中的笔记、总结以及知识分享">
  
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <title>
    JavaScript 内置对象 String 的 padStart() 和 padEnd() 方法 |
    
    种子的信仰</title>
  
    <link rel="shortcut icon" href="/your/favicon.ico">
  
  
<link rel="stylesheet" href="/your/css/style.css">

  
    
<link rel="stylesheet" href="/your/fancybox/jquery.fancybox.min.css">

  
  
<script src="/your/js/pace.min.js"></script>

<meta name="generator" content="Hexo 4.2.1"><link rel="alternate" href="/your/atom.xml" title="种子的信仰" type="application/atom+xml">
</head>

<body>
<main class="content">
  <section class="outer">
  <article id="post-string-prototype-padStart-and-padEnd" class="article article-type-post" itemscope itemprop="blogPost" data-scroll-reveal>

    <div class="article-inner">
        
            <header class="article-header">
                
  
    <h1 class="article-title" itemprop="name">
      JavaScript 内置对象 String 的 padStart() 和 padEnd() 方法
    </h1>
  
  




            </header>
            

                
                    <div class="article-meta">
                        <a href="/your/2020/08/14/string-prototype-padStart-and-padEnd/" class="article-date">
  <time datetime="2020-08-14T15:56:36.000Z" itemprop="datePublished">2020-08-14</time>
</a>
                            
  <div class="article-category">
    <a class="article-category-link" href="/your/categories/%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/">学习笔记</a> / <a class="article-category-link" href="/your/categories/%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/JavaScript/">JavaScript</a>
  </div>

                    </div>
                    

                        
                            
    <div class="tocbot"></div>





                                

                                    <div class="article-entry" itemprop="articleBody">
                                        


                                            

                                                
                                                                    <h2 id="padStart"><a href="#padStart" class="headerlink" title="padStart()"></a><code>padStart()</code></h2><p><code>padStart</code> 和 <code>padEnd</code> 方法是 <code>String.prototype</code> 上定义的方法, 在 <code>ECMAScript</code> 2017 (<code>ES7</code>) 中首次被定义; 两个方法都是返回新的字符串, 并且不会改变原来的值</p>
<h3 id="语法"><a href="#语法" class="headerlink" title="语法"></a>语法</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">str.padStart(targetLength [, padString])</span><br></pre></td></tr></table></figure>

<h3 id="作用"><a href="#作用" class="headerlink" title="作用:"></a>作用:</h3><p>用另一个字符串(<code>padString</code>)从当前字符串(<code>str</code>)<strong>左侧</strong>开始填充, 直到字符串(<code>str</code>)达到给定的长度(<code>targetLength</code>), 然后将新的字符串返回</p>
<p>例子:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> str = <span class="string">'2'</span></span><br><span class="line"><span class="keyword">const</span> newStr = str.padStart(<span class="number">2</span>, <span class="string">'0'</span>)</span><br><span class="line"><span class="built_in">console</span>.log(str) <span class="comment">// '2'</span></span><br><span class="line"><span class="built_in">console</span>.log(newStr) <span class="comment">// '02'</span></span><br></pre></td></tr></table></figure>

<h3 id="规则"><a href="#规则" class="headerlink" title="规则"></a>规则</h3><p><strong>1.</strong> 如果 <code>targetLength</code> 这个数值小于当前字符串(<code>str</code>)的长度, 则返回当前字符串</p>
<p>示例:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> str = <span class="string">'08'</span> <span class="comment">// str.length = 2</span></span><br><span class="line"><span class="keyword">const</span> newStr = str.padStart(<span class="number">1</span>, <span class="string">'LLLL'</span>) <span class="comment">// targetLength: 1</span></span><br><span class="line"><span class="built_in">console</span>.log(newStr) <span class="comment">// '08'</span></span><br></pre></td></tr></table></figure>

<p><strong>2.</strong> 如果填充字符串(<code>padString</code>)太长，使填充后的字符串长度超过了目标长度(<code>targetLength</code>)，则只保留最左侧的部分，其他部分会被截断</p>
<p>示例:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> str = <span class="string">'abc'</span></span><br><span class="line"><span class="keyword">const</span> newStr = str.padStart(<span class="number">6</span>, <span class="string">'0123'</span>)</span><br><span class="line"><span class="built_in">console</span>.log(newStr) <span class="comment">// '012abc'</span></span><br></pre></td></tr></table></figure>

<h3 id="兼容性"><a href="#兼容性" class="headerlink" title="兼容性"></a>兼容性</h3><p>兼容性并不理想, 在 ECMAScript 2017 (ES7) 中首次被定义。</p>
<p>查看 <a href="https://caniuse.com/#search=padStart" target="_blank" rel="noopener">https://caniuse.com/#search=padStart</a></p>
<img src="/your/2020/08/14/string-prototype-padStart-and-padEnd/20200815145303_start.jpg" class="" title="padStart 兼容性">

<p><strong>如果原生环境不支持该方法，在其他代码之前先运行下面的代码，将创建 <code>String.prototype.padStart()</code> 方法。</strong></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// https://github.com/uxitten/polyfill/blob/master/string.polyfill.js</span></span><br><span class="line"><span class="comment">// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart</span></span><br><span class="line"><span class="keyword">if</span> (!<span class="built_in">String</span>.prototype.padStart) &#123;</span><br><span class="line">    <span class="built_in">String</span>.prototype.padStart = <span class="function"><span class="keyword">function</span> <span class="title">padStart</span>(<span class="params">targetLength,padString</span>) </span>&#123;</span><br><span class="line">        targetLength = targetLength&gt;&gt;<span class="number">0</span>; <span class="comment">//floor if number or convert non-number to 0;</span></span><br><span class="line">        padString = <span class="built_in">String</span>((<span class="keyword">typeof</span> padString !== <span class="string">'undefined'</span> ? padString : <span class="string">' '</span>));</span><br><span class="line">        <span class="keyword">if</span> (<span class="keyword">this</span>.length &gt; targetLength) &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="built_in">String</span>(<span class="keyword">this</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">else</span> &#123;</span><br><span class="line">            targetLength = targetLength-<span class="keyword">this</span>.length;</span><br><span class="line">            <span class="keyword">if</span> (targetLength &gt; padString.length) &#123;</span><br><span class="line">                padString += padString.repeat(targetLength/padString.length); <span class="comment">//append to original to ensure we are longer than needed</span></span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">return</span> padString.slice(<span class="number">0</span>,targetLength) + <span class="built_in">String</span>(<span class="keyword">this</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="使用场景"><a href="#使用场景" class="headerlink" title="使用场景"></a>使用场景</h3><p>目前常见用于日期和时间字符串实现补0</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> date = <span class="keyword">new</span> <span class="built_in">Date</span>()</span><br><span class="line"><span class="keyword">let</span> month = <span class="string">`<span class="subst">$&#123;date.getMonth() + <span class="number">1</span>&#125;</span>`</span></span><br><span class="line"><span class="keyword">if</span> (month.length === <span class="number">1</span>) month = month.padStart(<span class="number">2</span>, <span class="string">'0'</span>) <span class="comment">// 用得好像鸡肋的. 哈哈..</span></span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">'month:'</span>, month) <span class="comment">// month: 08</span></span><br></pre></td></tr></table></figure>

<h2 id="padEnd"><a href="#padEnd" class="headerlink" title="padEnd()"></a><code>padEnd()</code></h2><p>用另一个字符串(<code>padString</code>)从当前字符串(<code>str</code>)<strong>右侧</strong>开始填充, 直到字符串(<code>str</code>)达到给定的长度(<code>targetLength</code>), 然后将新的字符串返回</p>
<p><code>padEnd</code> 和 <code>padStart</code> 语法, 作用, 规则基本上一致的, 不同的是 <code>padEnd</code>, 从<strong>右侧</strong>开始填充</p>
<h3 id="语法-1"><a href="#语法-1" class="headerlink" title="语法"></a>语法</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">str.padEnd(targetLength [, padString])</span><br></pre></td></tr></table></figure>

<p>例子: </p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> str = <span class="string">'23'</span></span><br><span class="line"><span class="keyword">const</span> newStr = str.padEnd(<span class="number">4</span>, <span class="string">'ABC'</span>)</span><br><span class="line"><span class="built_in">console</span>.log(newStr) <span class="comment">// 23AB</span></span><br></pre></td></tr></table></figure>

<h3 id="兼容性-1"><a href="#兼容性-1" class="headerlink" title="兼容性"></a>兼容性</h3><p>兼容和 <code>padStart</code> 一致, 查看 <a href="https://caniuse.com/#search=padEnd" target="_blank" rel="noopener">https://caniuse.com/#search=padEnd</a></p>
<p><strong>如果原生环境不支持该方法，在其他代码之前先运行下面的代码，将创建 <code>String.prototype.padEnd()</code> 方法。</strong></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// https://github.com/uxitten/polyfill/blob/master/string.polyfill.js</span></span><br><span class="line"><span class="comment">// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padEnd</span></span><br><span class="line"><span class="keyword">if</span> (!<span class="built_in">String</span>.prototype.padEnd) &#123;</span><br><span class="line">    <span class="built_in">String</span>.prototype.padEnd = <span class="function"><span class="keyword">function</span> <span class="title">padEnd</span>(<span class="params">targetLength,padString</span>) </span>&#123;</span><br><span class="line">        targetLength = targetLength&gt;&gt;<span class="number">0</span>; <span class="comment">//floor if number or convert non-number to 0;</span></span><br><span class="line">        padString = <span class="built_in">String</span>((<span class="keyword">typeof</span> padString !== <span class="string">'undefined'</span> ? padString: <span class="string">''</span>));</span><br><span class="line">        <span class="keyword">if</span> (<span class="keyword">this</span>.length &gt; targetLength) &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="built_in">String</span>(<span class="keyword">this</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">else</span> &#123;</span><br><span class="line">            targetLength = targetLength-<span class="keyword">this</span>.length;</span><br><span class="line">            <span class="keyword">if</span> (targetLength &gt; padString.length) &#123;</span><br><span class="line">                padString += padString.repeat(targetLength/padString.length); <span class="comment">//append to original to ensure we are longer than needed</span></span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">return</span> <span class="built_in">String</span>(<span class="keyword">this</span>) + padString.slice(<span class="number">0</span>,targetLength);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>总结</strong></p>
<p>翻看 <code>uView ui</code> 源码才知道有 <code>padStart</code> 这么一个方法的存在, 去 MDN 查到了相关的文档学习, 目前不推荐使用.</p>
<p>看源码很有意思, 可以学习到一些开发骚技巧来补充自己的不足.</p>
<p><strong>参考</strong><br><a href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/String/padStart" target="_blank" rel="noopener">String.prototype.padStart() - MDN</a><br><a href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/String/padEnd" target="_blank" rel="noopener">String.prototype.padEnd() - MDN</a></p>

                                                                        
                                    </div>
                                    <footer class="article-footer">
                                        <!-- 注释 - 分享按钮 -->
                                        <!-- <a data-url="http://liguoyou.gitee.io/your/2020/08/14/string-prototype-padStart-and-padEnd/" data-id="cl0gvpjqy0016m4on9ulgevaq" class="article-share-link">
                                            分享
                                        </a> -->
                                        
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/your/tags/padEnd/" rel="tag">padEnd</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/your/tags/padStart/" rel="tag">padStart</a></li></ul>

                                    </footer>

    </div>

    
        
  <nav class="article-nav">
    
      <a href="/your/2020/08/20/uni-app-display-flex-v-show-invalid/" class="article-nav-link">
        <strong class="article-nav-caption">前一篇</strong>
        <div class="article-nav-title">
          
            uni-app 给 view 设置 display:flex 后, v-show=&#34;false&#34; 在微信小程序中失效
          
        </div>
      </a>
    
    
      <a href="/your/2020/08/10/install-yarn-through-nodejs-and-npm/" class="article-nav-link">
        <strong class="article-nav-caption">后一篇</strong>
        <div class="article-nav-title">使用 Node.js 和 npm 安装和配置 Yarn</div>
      </a>
    
  </nav>


            

                
                    
                        
  <div class="gitalk" id="gitalk-container"></div>
  <p style="color: #999; font-size: 12px; text-align: center;">
    第三方评论系统 -- Gitalk: 偶尔可能出现加载失败的情况, 您可以选择刷新或者前往 
    <a href="https://github.com/liguoyou/your/issues" target="_blank">issues</a>
    提交和查看评论
  </p>
  
<link rel="stylesheet" href="https://unpkg.com/gitalk/dist/gitalk.css">

  
<script src="https://unpkg.com/gitalk/dist/gitalk.min.js"></script>

  
<script src="https://cdn.bootcss.com/blueimp-md5/2.10.0/js/md5.min.js"></script>

  <script type="text/javascript">
    var gitalk = new Gitalk({
      clientID: '2e731d2b04096a7c71ab',
      clientSecret: '41e2e15eb8edebd8efd5a6da558a44d60f33468a',
      repo: 'your',
      owner: 'liguoyou',
      admin: ['liguoyou'],
      // id: location.pathname,      // Ensure uniqueness and length less than 50
      id: md5(location.pathname),
      distractionFreeMode: false,  // Facebook-like distraction free mode
      pagerDirection: 'last'
    })

  gitalk.render('gitalk-container')
  </script>

                            

</article>
</section>
  <footer class="footer">
  <div class="outer">
    <div class="float-right">
      <ul class="list-inline">
  
    <li><i class="fe fe-smile-alt"></i> <span id="busuanzi_value_site_uv"></span></li>
  
    <li><i class="fe fe-bookmark"></i> <span id="busuanzi_value_page_pv"></span></li>
  
</ul>
    </div>
    <ul class="list-inline">
      <li>&copy; 2022 种子的信仰</li>
      <li>Powered by <a href="http://hexo.io/" target="_blank">Hexo</a></li>
      <li>Theme  <a href="https://github.com/zhwangart/hexo-theme-ocean" target="_blank" rel="noopener">Ocean</a></li>
    </ul>
  </div>
</footer>

</main>
<aside class="sidebar">
  <button class="navbar-toggle"></button>
<nav class="navbar">
  
    <div class="logo">
      <a href="/your/"><img src="/your/images/logo.png" alt="种子的信仰"></a>
    </div>
  
  <ul class="nav nav-main">
    
      <li class="nav-item">
        <a class="nav-item-link" href="/your/">首页</a>
      </li>
    
      <li class="nav-item">
        <a class="nav-item-link" href="/your/archives">时间轴</a>
      </li>
    
      <li class="nav-item">
        <a class="nav-item-link" href="/your/gallery">相册</a>
      </li>
    
      <li class="nav-item">
        <a class="nav-item-link" href="/your/categories">分类</a>
      </li>
    
      <li class="nav-item">
        <a class="nav-item-link" href="/your/tags">标签</a>
      </li>
    
      <li class="nav-item">
        <a class="nav-item-link" href="/your/about">关于</a>
      </li>
    
    <li class="nav-item">
      <a class="nav-item-link nav-item-search" title="搜索">
        <i class="fe fe-search"></i>
        搜索
      </a>
    </li>
  </ul>
</nav>
<nav class="navbar navbar-bottom">
  <ul class="nav">
    <li class="nav-item">
      <div class="totop" id="totop">
  <i class="fe fe-rocket"></i>
</div>
    </li>
    <li class="nav-item">
      
        <a class="nav-item-link" target="_blank" href="/your/atom.xml" title="RSS Feed">
          <i class="fe fe-feed"></i>
        </a>
      
    </li>
  </ul>
</nav>
<div class="search-form-wrap">
  <div class="local-search local-search-plugin">
  <input type="search" id="local-search-input" class="local-search-input" placeholder="请输入关键词...">
  <div id="local-search-result" class="local-search-result"></div>
</div>
</div>
</aside>

<script src="/your/js/jquery-2.0.3.min.js"></script>


<script src="/your/js/jquery.justifiedGallery.min.js"></script>


<script src="/your/js/lazyload.min.js"></script>


<script src="/your/js/busuanzi-2.3.pure.min.js"></script>


  
<script src="/your/fancybox/jquery.fancybox.min.js"></script>




  
<script src="/your/js/tocbot.min.js"></script>

  <script>
    // Tocbot_v4.7.0  http://tscanlin.github.io/tocbot/
    tocbot.init({
      tocSelector: '.tocbot',
      contentSelector: '.article-entry',
      headingSelector: 'h1, h2, h3, h4, h5, h6',
      hasInnerContainers: true,
      scrollSmooth: true,
      positionFixedSelector: '.tocbot',
      positionFixedClass: 'is-position-fixed',
      fixedSidebarOffset: 'auto',
    });
  </script>


<script src="/your/js/ocean.js"></script>


</body>
</html>